import { Page, Route } from '@playwright/test';
import { TestHelpers } from './test-helpers';

export class ApiMock {
  private page: Page;
  private mockRoutes: Map<string, Route> = new Map();

  constructor(page: Page) {
    this.page = page;
  }

  /**
   * 模拟API响应
   */
  async mockApi(url: string, responseData: any, status: number = 200, headers: Record<string, string> = {}): Promise<void> {
    await this.page.route(url, async (route) => {
      await route.fulfill({
        status,
        headers: {
          'Content-Type': 'application/json',
          ...headers
        },
        body: JSON.stringify(responseData)
      });
    });

    console.log(`🎭 Mock API: ${url} -> ${status}`);
  }

  /**
   * 模拟登录API
   */
  async mockLogin(success: boolean = true, userData?: any): Promise<void> {
    const loginResponse = success
      ? {
        success: true,
        data: {
          token: 'mock-jwt-token',
          user: userData || {
            id: 'test-user-id',
            username: 'testuser',
            email: 'test@example.com',
            role: 'user'
          }
        }
      }
      : {
        success: false,
        error: '登录失败',
        message: '用户名或密码错误'
      };

    await this.mockApi('**/api/auth/login', loginResponse, success ? 200 : 401);
  }

  /**
   * 模拟Agent API
   */
  async mockAgents(agents: any[] = []): Promise<void> {
    const mockAgents = agents.length > 0
      ? agents
      : [
          {
            id: 'test-agent-1',
            name: '测试Agent 1',
            description: '用于测试的AI Agent',
            model: 'gpt-4',
            status: 'active',
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString()
          },
          {
            id: 'test-agent-2',
            name: '测试Agent 2',
            description: '另一个测试Agent',
            model: 'gpt-3.5-turbo',
            status: 'inactive',
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString()
          }
        ];

    await this.mockApi('**/api/agents', {
      success: true,
      data: mockAgents,
      total: mockAgents.length
    });
  }

  /**
   * 模拟模型配置API
   */
  async mockModelConfigs(configs: any[] = []): Promise<void> {
    const mockConfigs = configs.length > 0
      ? configs
      : [
          {
            id: 'model-config-1',
            name: 'GPT-4',
            provider: 'OpenAI',
            model: 'gpt-4',
            apiKey: 'sk-***',
            baseUrl: 'https://api.openai.com/v1',
            isActive: true,
            createdAt: new Date().toISOString()
          },
          {
            id: 'model-config-2',
            name: 'Claude',
            provider: 'Anthropic',
            model: 'claude-3-sonnet',
            apiKey: 'sk-***',
            baseUrl: 'https://api.anthropic.com',
            isActive: false,
            createdAt: new Date().toISOString()
          }
        ];

    await this.mockApi('**/api/model-configs', {
      success: true,
      data: mockConfigs,
      total: mockConfigs.length
    });
  }

  /**
   * 模拟对话API
   */
  async mockConversations(conversations: any[] = []): Promise<void> {
    const mockConversations = conversations.length > 0
      ? conversations
      : [
          {
            id: 'conversation-1',
            title: '测试对话',
            agentId: 'test-agent-1',
            messages: [
              {
                role: 'user',
                content: '你好',
                timestamp: new Date().toISOString()
              },
              {
                role: 'assistant',
                content: '你好！我是AI助手',
                timestamp: new Date().toISOString()
              }
            ],
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString()
          }
        ];

    await this.mockApi('**/api/conversations', {
      success: true,
      data: mockConversations,
      total: mockConversations.length
    });
  }

  /**
   * 模拟系统监控API
   */
  async mockMonitoringData(): Promise<void> {
    const monitoringData = {
      success: true,
      data: {
        system: {
          cpu: 45.2,
          memory: 67.8,
          disk: 34.5,
          uptime: '2h 15m'
        },
        performance: {
          responseTime: 245,
          throughput: 1250,
          errorRate: 0.02
        },
        agents: {
          total: 15,
          active: 12,
          inactive: 3
        },
        conversations: {
          total: 1234,
          today: 45,
          averageLength: 8.5
        }
      }
    };

    await this.mockApi('**/api/agent-platform/performance/**', monitoringData);
  }

  /**
   * 模拟MCP服务器API
   */
  async mockMcpServers(servers: any[] = []): Promise<void> {
    const mockServers = servers.length > 0
      ? servers
      : [
          {
            id: 'mcp-server-1',
            name: '测试MCP服务器',
            url: 'http://localhost:8080',
            status: 'connected',
            capabilities: ['tools', 'resources'],
            lastConnected: new Date().toISOString()
          }
        ];

    await this.mockApi('**/api/mcp-servers', {
      success: true,
      data: mockServers,
      total: mockServers.length
    });
  }

  /**
   * 模拟错误响应
   */
  async mockError(url: string, status: number = 500, message: string = 'Internal Server Error'): Promise<void> {
    await this.mockApi(url, {
      success: false,
      error: message,
      timestamp: new Date().toISOString()
    }, status);
  }

  /**
   * 模拟网络延迟
   */
  async mockDelay(url: string, delay: number = 1000): Promise<void> {
    await this.page.route(url, async (route) => {
      await new Promise(resolve => setTimeout(resolve, delay));
      await route.continue();
    });

    console.log(`⏱️  Mock延迟: ${url} -> ${delay}ms`);
  }

  /**
   * 清除所有Mock
   */
  async clearAllMocks(): Promise<void> {
    await this.page.unrouteAll();
    this.mockRoutes.clear();
    console.log('🧹 清除所有Mock');
  }

  /**
   * 模拟文件上传
   */
  async mockFileUpload(url: string, response: any): Promise<void> {
    await this.mockApi(url, response, 200, {
      'Content-Type': 'multipart/form-data'
    });
  }

  /**
   * 模拟WebSocket连接
   */
  async mockWebSocket(url: string, messages: any[] = []): Promise<void> {
    // WebSocket mocking需要更复杂的设置，这里提供基础框架
    console.log(`🔌 Mock WebSocket: ${url}`);
    // 实际WebSocket mocking需要使用WebSocket库或Playwright的WebSocket API
  }

  /**
   * 验证API调用
   */
  async verifyApiCall(url: string, method: string = 'GET'): Promise<boolean> {
    let apiCalled = false;

    await this.page.route(url, async (route) => {
      const request = route.request();
      if (request.method() === method) {
        apiCalled = true;
        console.log(`✅ API调用验证: ${method} ${url}`);
      }
      await route.continue();
    });

    return apiCalled;
  }
}